/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

import process from 'process';

import { HvigorDaemonLogger } from '../log/hvigor-daemon-log.js';

import { DaemonState } from './daemon-info.js';
import { DefaultDaemonRegistry } from './default-daemon-registry.js';

const _log = HvigorDaemonLogger.getLogger('daemon');

class DaemonServerRegistry extends DefaultDaemonRegistry {
  constructor() {
    super(_log);
  }

  updateDaemonProcessState(daemonState: DaemonState, stateChangeInfo?: string): void {
    const curProcessDaemonInfo = this.getDaemonInfoByPid(process.pid);
    if (!curProcessDaemonInfo) {
      _log.debug('hvigor daemon: Cannot transform process state. Unable to find daemon info from registry.');
      return;
    }
    const newDaemonInfo = {
      ...curProcessDaemonInfo,
      state: daemonState,
      info: stateChangeInfo,
    };
    _log.debug(`hvigor daemon: Update daemon info in registry. daemonInfo=${JSON.stringify(newDaemonInfo)}`);
    this.setInfo(curProcessDaemonInfo.keyId, newDaemonInfo);
  }

  getAllPortInUsed(): number[] {
    return this.getInfos()
      .filter((daemonInfo) => {
        return daemonInfo.state !== DaemonState.BROKEN && daemonInfo.state !== DaemonState.STOPPED;
      })
      .map((daemonInfo) => {
        return daemonInfo.port;
      });
  }
}

export const defaultDaemonServerRegistry = new DaemonServerRegistry();
